/*
 * ECARX Technology Limited is the owner of the copyright and the trade secret of this software.
 * Without permission, no one has the right to obtain, disclose or use this software in any way.
 */
package com.ecarx.systemui.plugin.ui.statusbar

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.content.res.ResourcesCompat
import com.ecarx.systemui.plugin.R
import com.ecarx.systemui.plugin.controller.BluetoothController
import com.ecarx.systemui.plugin.ui.custom.SystemBarButton
import com.ecarx.systemui.plugin.ui.dialog.base.DialogManager
import com.ecarx.systemui.plugin.utils.LogUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class BluetoothView : SystemBarButton {

    companion object {
        private const val TAG = "BluetoothView"
    }

    constructor(context: Context?) : this(context!!, null) {}
    constructor(context: Context?, attrs: AttributeSet?) : this(context!!, attrs, 0) {}
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(
        context!!,
        attrs,
        defStyleAttr
    ) {

    }

    override fun getContentDescriptionString(): String {
        return "BluetoothView"
    }

    override fun initView() {
        super.initView()

        setOnClickListener { v: View? ->
            showPopupWindow()
        }
    }

    private fun showPopupWindow() {
        val locations = IntArray(2)
        getLocationOnScreen(locations)
        locations[0] = locations[0] - getPopupWindowWidth() / 2
        DialogManager.getDialogManager().showBtWifiDialog(context, locations, 1)
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()

        val isEnable = BluetoothController.getInstance().isEnable
        extracted(isEnable)
        visibility = View.VISIBLE

        BluetoothController.getInstance().listenBtEnableChanged(object : BluetoothController.OnBtEnableListener {
            override fun onBtEnable(enable: Boolean) {
                extracted(enable)
            }
        })

        BluetoothController.getInstance().listenBtTypeChanged(object : BluetoothController.OnBtTypeListener {
            override fun onBtType() {
                extracted(true)

            }
        })


        val intentFilter = IntentFilter("com.ecarx.systemuiplugin.dialog.BLUETOOTH")
        context.registerReceiver(object : BroadcastReceiver() {
            override fun onReceive(context: Context?, intent: Intent?) {
                if (context?.packageName.equals("com.android.systemui")||context?.packageName.equals("com.ecarx.mulitmedia")) {
                    showPopupWindow()
                } else {
                    Log.d(TAG, "not permission show")
                }
            }
        }, intentFilter)
    }

    private fun extracted(enable:Boolean) {
        CoroutineScope(Dispatchers.IO).launch {
            val type2 = BluetoothController.getInstance().BTDeviceType()
            withContext(Dispatchers.Main) {
                updateIconStatus(enable, type2)
            }
        }
    }

    fun updateIconStatus(enabled:Boolean,type:Int){
        if(enabled){
            LogUtils.d(TAG,  "init: showDevices   ${type}")
            setImageDrawable(
                ResourcesCompat
                    .getDrawable(
                        resources,
                         when(type){
                               0->R.drawable.ic_bt_on
                               1->R.drawable.ic_bt_mp_on
                               2->R.drawable.ic_bt_music_on
                               3->R.drawable.ic_bt_phone_on
                             else -> {
                                R.drawable.ic_bt_on
                             }
                         }
                       , context.theme
                    )
            )

        }else{
            setImageDrawable(
                ResourcesCompat
                    .getDrawable(
                        resources,
                      R.drawable.ic_bt_off,
                        context.theme
                    )
            )
        }

    }


    private fun getPopupWindowWidth() : Int{
        return resources.getDimension(R.dimen.dp_710).toInt()
    }
}